// pages/scenes/scenes.js
const { sceneAPI } = require('../../utils/api.js')

Page({
  data: {
    searchKeyword: '',
    currentCategory: 'all',
    sortIndex: 0,
    sortOptions: ['默认排序', '使用频率', '创建时间', '名称排序'],
    recommendedScenes: [],
    allScenes: [],
    filteredScenes: [],
    activatingScene: false,
    activatingSceneName: ''
  },

  onLoad(options) {
    this.loadScenesData()
    
    // 如果有房间ID参数，筛选该房间的场景
    if (options.roomId) {
      this.setData({ currentCategory: 'custom' })
    }
  },

  onShow() {
    this.loadScenesData()
  },

  // 加载场景数据
  async loadScenesData() {
    try {
      wx.showLoading({ title: '加载中...' })
      
      const scenes = await sceneAPI.getSceneList()
      const enrichedScenes = await this.enrichSceneData(scenes)
      
      // 分离推荐场景和全部场景
      const recommendedScenes = enrichedScenes.filter(scene => scene.isRecommended)
      const allScenes = enrichedScenes
      
      this.setData({
        recommendedScenes,
        allScenes,
        filteredScenes: this.filterScenes(allScenes)
      })
      
      wx.hideLoading()
    } catch (error) {
      console.error('加载场景数据失败:', error)
      wx.hideLoading()
      wx.showToast({ title: '加载失败', icon: 'error' })
    }
  },

  // 丰富场景数据
  async enrichSceneData(scenes) {
    const app = getApp()
    const devices = app.globalData.deviceList
    
    return scenes.map(scene => {
      const sceneDevices = scene.devices.map(deviceId => {
        const device = devices.find(d => d.id === deviceId)
        return device ? {
          ...device,
          targetState: this.getSceneDeviceState(scene.id, deviceId)
        } : null
      }).filter(Boolean)
      
      const categoryMap = {
        'home': 'daily',
        'away': 'security',
        'sleep': 'daily',
        'entertainment': 'entertainment'
      }
      
      const categoryTextMap = {
        'daily': '日常',
        'entertainment': '娱乐',
        'security': '安防',
        'custom': '自定义'
      }
      
      return {
        ...scene,
        devices: sceneDevices,
        deviceCount: sceneDevices.length,
        category: categoryMap[scene.id] || 'custom',
        categoryText: categoryTextMap[categoryMap[scene.id]] || '自定义',
        isActive: wx.getStorageSync(`scene_active_${scene.id}`) || false,
        isFavorite: wx.getStorageSync(`scene_favorite_${scene.id}`) || false,
        isRecommended: ['home', 'away'].includes(scene.id),
        usageCount: wx.getStorageSync(`scene_usage_${scene.id}`) || 0,
        background: this.getSceneBackground(scene.id)
      }
    })
  },

  // 获取场景设备目标状态
  getSceneDeviceState(sceneId, deviceId) {
    const stateMap = {
      'home': {
        'light-001': 'on',
        'ac-001': 'on',
        'tv-001': 'off'
      },
      'away': {
        'light-001': 'off',
        'light-002': 'off',
        'ac-001': 'off',
        'tv-001': 'off'
      },
      'sleep': {
        'light-001': 'off',
        'light-002': 'on',
        'ac-001': 'on'
      },
      'entertainment': {
        'light-001': 'on',
        'tv-001': 'on'
      }
    }
    
    return stateMap[sceneId]?.[deviceId] || 'off'
  },

  // 获取场景背景图
  getSceneBackground(sceneId) {
    const backgroundMap = {
      'home': '/images/scenes/home-bg.jpg',
      'away': '/images/scenes/away-bg.jpg',
      'sleep': '/images/scenes/sleep-bg.jpg',
      'entertainment': '/images/scenes/entertainment-bg.jpg'
    }
    return backgroundMap[sceneId] || '/images/scenes/default-bg.jpg'
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword,
      filteredScenes: this.filterScenes(this.data.allScenes)
    })
  },

  // 清除搜索
  onClearSearch() {
    this.setData({
      searchKeyword: '',
      filteredScenes: this.filterScenes(this.data.allScenes)
    })
  },

  // 分类切换
  onCategoryChange(e) {
    const category = e.currentTarget.dataset.category
    this.setData({
      currentCategory: category,
      filteredScenes: this.filterScenes(this.data.allScenes)
    })
  },

  // 排序切换
  onSortChange(e) {
    const index = e.detail.value
    this.setData({
      sortIndex: index,
      filteredScenes: this.sortScenes(this.filterScenes(this.data.allScenes))
    })
  },

  // 过滤场景
  filterScenes(scenes) {
    let filtered = scenes
    
    // 关键词过滤
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase()
      filtered = filtered.filter(scene => 
        scene.name.toLowerCase().includes(keyword) ||
        scene.description.toLowerCase().includes(keyword)
      )
    }
    
    // 分类过滤
    if (this.data.currentCategory !== 'all') {
      filtered = filtered.filter(scene => scene.category === this.data.currentCategory)
    }
    
    return this.sortScenes(filtered)
  },

  // 排序场景
  sortScenes(scenes) {
    const sortType = this.data.sortIndex
    
    switch(sortType) {
      case 0: // 默认排序
        return scenes.sort((a, b) => {
          if (a.isRecommended !== b.isRecommended) {
            return b.isRecommended - a.isRecommended
          }
          return b.usageCount - a.usageCount
        })
        
      case 1: // 使用频率
        return scenes.sort((a, b) => b.usageCount - a.usageCount)
        
      case 2: // 创建时间
        return scenes.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        
      case 3: // 名称排序
        return scenes.sort((a, b) => a.name.localeCompare(b.name))
        
      default:
        return scenes
    }
  },

  // 场景点击事件
  onSceneTap(e) {
    const scene = e.currentTarget.dataset.scene
    this.activateScene(scene)
  },

  // 场景开关切换
  onSceneToggle(e) {
    const sceneId = e.currentTarget.dataset.sceneId
    const isActive = e.detail.value
    const scene = this.data.allScenes.find(s => s.id === sceneId)
    
    if (scene) {
      if (isActive) {
        this.activateScene(scene)
      } else {
        this.deactivateScene(scene)
      }
    }
  },

  // 激活场景
  async activateScene(scene) {
    this.setData({
      activatingScene: true,
      activatingSceneName: scene.name
    })
    
    try {
      // 调用API激活场景
      await sceneAPI.activateScene(scene.id)
      
      // 更新设备状态
      await this.executeSceneDevices(scene)
      
      // 更新场景状态
      this.updateSceneState(scene.id, true)
      
      // 更新使用次数
      this.updateSceneUsage(scene.id)
      
      wx.showToast({
        title: `${scene.name} 已激活`,
        icon: 'success'
      })
      
    } catch (error) {
      console.error('激活场景失败:', error)
      wx.showToast({
        title: '激活失败',
        icon: 'error'
      })
    } finally {
      this.setData({
        activatingScene: false,
        activatingSceneName: ''
      })
      
      // 刷新数据
      this.loadScenesData()
    }
  },

  // 停用场景
  deactivateScene(scene) {
    this.updateSceneState(scene.id, false)
    
    wx.showToast({
      title: `${scene.name} 已停用`,
      icon: 'success'
    })
    
    this.loadScenesData()
  },

  // 执行场景设备控制
  async executeSceneDevices(scene) {
    const app = getApp()
    
    for (const device of scene.devices) {
      if (device.status !== 'offline') {
        const targetState = this.getSceneDeviceState(scene.id, device.id)
        app.updateDeviceStatus(device.id, {
          ...device.status,
          powerState: targetState
        })
        
        // 模拟设备控制延迟
        await new Promise(resolve => setTimeout(resolve, 200))
      }
    }
  },

  // 更新场景状态
  updateSceneState(sceneId, isActive) {
    wx.setStorageSync(`scene_active_${sceneId}`, isActive)
    
    const scenes = this.data.allScenes.map(scene =>
      scene.id === sceneId ? { ...scene, isActive } : scene
    )
    
    this.setData({
      allScenes: scenes,
      filteredScenes: this.filterScenes(scenes)
    })
  },

  // 更新场景使用次数
  updateSceneUsage(sceneId) {
    const currentCount = wx.getStorageSync(`scene_usage_${sceneId}`) || 0
    wx.setStorageSync(`scene_usage_${sceneId}`, currentCount + 1)
  },

  // 收藏点击事件
  onFavoriteTap(e) {
    e.stopPropagation()
    const sceneId = e.currentTarget.dataset.sceneId
    const currentFavorite = wx.getStorageSync(`scene_favorite_${sceneId}`) || false
    
    wx.setStorageSync(`scene_favorite_${sceneId}`, !currentFavorite)
    
    wx.showToast({
      title: !currentFavorite ? '已收藏' : '已取消收藏',
      icon: 'success'
    })
    
    this.loadScenesData()
  },

  // 编辑场景
  onSceneEdit(e) {
    e.stopPropagation()
    const sceneId = e.currentTarget.dataset.sceneId
    
    wx.navigateTo({
      url: `/pages/scene-edit/scene-edit?sceneId=${sceneId}`
    })
  },

  // 编辑场景列表
  onEditScenes() {
    wx.showActionSheet({
      itemList: ['排序场景', '管理推荐', '批量操作'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.onSortScenes()
            break
          case 1:
            this.onManageRecommended()
            break
          case 2:
            this.onBatchOperations()
            break
        }
      }
    })
  },

  // 创建场景
  onCreateScene() {
    wx.navigateTo({
      url: '/pages/scene-create/scene-create'
    })
  }
})